//
//  XTUtility+Device.m
//  XTUtilityKit
//
//  Created by Tong on 2017/6/2.
//  Copyright © 2017年 Tong. All rights reserved.
//

#import "XTUtility+Device.h"

#import "XTUtility+Keychain.h"

@import AdSupport;

static NSString *const kIdfaService = @"com.tong.idfa.keychain";

@implementation XTUtility (Device)

+ (NSString *)getDeviceIdfa
{
    /** 1、读取 keychain 缓存 */
    NSString *deviceId = [self getIdfaStringFromKeychain];
    
    if ([self checkIdfaStringIsValid:deviceId]) {
        return deviceId;
    }
    
    /** 2、取用户 IDFA,如果用户关闭IDFA则生成UUID当成IDFA */
    if ([ASIdentifierManager sharedManager].advertisingTrackingEnabled) {
        
        deviceId = [[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString] lowercaseString];
        
    } else {
        /** 3、生成UUID */
        deviceId = [self getUUID];
    }
    
    if (![self checkIdfaStringIsValid:deviceId]) {
        return nil;
    }
    
    /** 保存到 Keychain */
    [self saveData:deviceId toKeychainWithService:kIdfaService];
    
    return deviceId;
}



/**
 获取 Keychain 里的idfa
 */
+ (NSString *)getIdfaStringFromKeychain
{
    NSString *idfaString = [XTUtility getDataFromKeychainWithService:kIdfaService];
    
    if ([self checkIdfaStringIsValid:idfaString]) {
        return idfaString;
    }
    return nil;
}


/**
 检查 Idfa 是否有效
 */
+ (BOOL)checkIdfaStringIsValid:(NSString *)idfaString
{
    BOOL isValid = NO;
    
    if (idfaString && idfaString.length != 0 && ![idfaString isEqualToString:@"00000000-0000-0000-0000-000000000000"]) {
        isValid = YES;
    }
    return isValid;
}


/**
 获取 UUID
 */
+ (NSString *)getUUID
{
    CFUUIDRef uuid_ref = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef uuid_string_ref= CFUUIDCreateString(kCFAllocatorDefault, uuid_ref);
    CFRelease(uuid_ref);
    
    NSString *uuid = [NSString stringWithString:(__bridge NSString*)uuid_string_ref];
    if (![self checkIdfaStringIsValid:uuid]) {
        uuid = @"";
    }
    CFRelease(uuid_string_ref);
    
    return [uuid lowercaseString];
}

@end
